package com.example.featuresdk.view

import android.content.Intent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.featuresdk.R
import com.example.featuresdk.core.AbstractFeatureSDK
import com.example.featuresdk.viewmodel.NavigationViewModel

@Composable
inline fun FullScreen(navigationViewModel: NavigationViewModel, content: @Composable () -> Unit) {

    Column(modifier = Modifier.background(Color.Transparent).fillMaxSize()) {
        content()
    }
}


@Composable
fun AppHeaderFeatureView(navigationViewModel: NavigationViewModel){
    val navController = navigationViewModel.navHostController
    Row(modifier = Modifier
        .height(navigationViewModel.appHeaderBarHeightDp.dp)
        .background(Color.LightGray)
        .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically) {

        //Display the title of current feature
        val titleWidthDp = 120
        Spacer(modifier = Modifier.width(((navigationViewModel.screenWithDp - titleWidthDp) / 2).dp))
        Text(text = navigationViewModel.selectedPrimaryFeatureTitle.value, modifier = Modifier
            .width(titleWidthDp.dp)
            .fillMaxHeight()
            .background(Color.Transparent)
            .padding(8.dp)
            .scale(1.2f, 1.2f),
            textAlign = TextAlign.Center,
            fontWeight = FontWeight.Bold
        )

        val appIconWidthDp = 34
        Spacer(modifier = Modifier.width(((navigationViewModel.screenWithDp - titleWidthDp) / 2 - appIconWidthDp * 2).dp))

        FeatureEntry(R.drawable.ic_search, onClick = {
            navController.navigate("${navigationViewModel.activeContextualFeatureKey.value}/search") {
                launchSingleTop = true
            }
        })
    }
}

@Composable
inline fun HeaderBackFeatureEntry(navigationViewModel: NavigationViewModel){
    FeatureEntry(R.drawable.ic_back, onClick = {
        navigationViewModel.navHostController.popBackStack()
    })
}

@Composable
inline fun FeatureEntry(icon: Int, crossinline onClick:()->Unit) {

    Spacer(modifier = Modifier.width(2.dp))
    Image(painter = painterResource(icon),
        contentDescription = "",
        modifier = Modifier
            .width(30.dp)
            .height(30.dp)
            .clickable { onClick() }
    )
    Spacer(modifier = Modifier.width(2.dp))
}

@OptIn(ExperimentalUnitApi::class)
@Composable
inline fun BottomFeatureEntry(selected: Boolean = false, featureSDK: AbstractFeatureSDK) {
    Column (modifier = Modifier
        .background(Color.Transparent),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally){

        Image(painter = painterResource(featureSDK.entryImageId(selected)),
            contentDescription = "",
            modifier = Modifier
                .width(30.dp)
                .height(30.dp)
        )

        Text(text = featureSDK.label(),
            color = if (selected) Color.Red else Color.Black,
            fontSize = TextUnit(3f, TextUnitType.Em),
            fontStyle = FontStyle.Normal,
            fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal
        )
    }
}

@Composable
inline fun SubFeatureEntry(selected: Boolean = false, featureSDK: AbstractFeatureSDK) {
    Row (modifier = Modifier
        .background(Color.Transparent)){

        Image(painter = painterResource(featureSDK.entryImageId(selected)),
            contentDescription = "",
            modifier = Modifier
                .width(40.dp)
                .height(40.dp)
        )

        Text(text = featureSDK.label(),
            color = if (selected) Color.Red else Color.Black,
            fontStyle = FontStyle.Normal,
            fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal
        )
    }
}

@Composable
inline fun AppBottomNavigation(navigationViewModel: NavigationViewModel){


    Spacer(modifier = Modifier.height(navigationViewModel.appBottomSpacerHeightDp.dp))
}

@Composable
fun AppBottomNavigationView(navigationViewModel: NavigationViewModel){

        val navController = navigationViewModel.navHostController

        TabRow(selectedTabIndex = navigationViewModel.selectedPrimaryFeatureTabIndex.value,
            modifier = Modifier
                .height(navigationViewModel.appBottomBarHeightDp.dp)
                .fillMaxWidth(),
            backgroundColor = Color.White,
            contentColor = Color.Black) {

            navigationViewModel.primaryFeatures.forEachIndexed { index, feature ->
                Tab(selected = false,
                    modifier = Modifier.width(40.dp),
                    onClick = {
//                    //update the view model to notify app footer TabRow to switch to the selected tab
                        navigationViewModel.selectedPrimaryFeatureTabIndex.value = index
//                    //update the view model to notify app header to refresh the title
                        navigationViewModel.selectedPrimaryFeatureTitle.value = feature.label()
//                    //store the active master feature key for contextual features
                        navigationViewModel.activeContextualFeatureKey.value = feature.featureKey()

                        //navigate to the destination specified by the 'route' parameter
                        navController.navigate("${feature.featureKey()}") {

                            // Pop up to the start destination of the graph to
                            // avoid building up a large stack of destinations
                            // on the back stack as users select items
                            popUpTo(navController.graph.findStartDestination().id) {
                                // save the back stack and state of all destinations between the current
                                // destination and the start destination for later restoration via 'restoreState = true'
                                saveState = true

                                //keep the start destination in the back stack,
                                // otherwise we can't restore its state when revisit the destination
                                inclusive = false
                            }

                            // launch to the destination as single-top
                            // i.e. there will be at most one copy of the given destination on the top of the back stack
                            // to avoid multiple copies of the same destination when re-selecting the same tab entry
                            launchSingleTop = true

                            //Restore any state previously saved by the PopupToBuilder.saveState for the destination.
                            //Please note that the destination needs to still exist in the back stack,
                            //otherwise it will raise an IllegalStateException
                            restoreState = true
                        }
                    })
                {
                    BottomFeatureEntry(index == navigationViewModel.selectedPrimaryFeatureTabIndex.value,
                        feature)
                }
            }
        }

        Spacer(modifier = Modifier.height(navigationViewModel.appBottomSpacerHeightDp.dp))

        AppBottomFeatureSelector(navigationViewModel, navController)

}

@Composable
fun AppBottomFeatureSelector(navigationViewModel: NavigationViewModel, navController: NavHostController){

    //back navigation: update the selected tab index when system back is triggered or when startup
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val backEntryRoute = navBackStackEntry?.arguments?.get("android-support-nav:controller:deepLinkIntent")
//        Log.i("***backEntryRoute****","${navBackStackEntry?.arguments}")
    //Bundle[{android-support-nav:controller:deepLinkIntent=Intent { dat=android-app://androidx.navigation/Book }}]

    var currentEntryRoute:String? = navController.graph.startDestinationRoute

    //backEntryRoute is null when the app starts up
    backEntryRoute?.let { currentEntryRoute = (it as Intent).dataString?.replace("android-app://androidx.navigation/","") }

//        Log.i("***currentEntryRoute****","$currentEntryRoute")

    currentEntryRoute?.let {
        navigationViewModel.primaryFeatures.forEachIndexed { index, feature ->
            if(currentEntryRoute!!.startsWith(feature.featureKey())) {
                navigationViewModel.selectedPrimaryFeatureTabIndex.value = index
                navigationViewModel.selectedPrimaryFeatureTitle.value = feature.label()
                navigationViewModel.activeContextualFeatureKey.value = feature.featureKey()
            }
        }
    }
}